package com.supinfo.youfood.pages.user.view;

import java.rmi.RemoteException;
import java.util.Arrays;
import java.util.List;

import javax.xml.rpc.ServiceException;

import org.apache.log4j.Logger;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.ListDataProvider;

import com.supinfo.food.entities.User;
import com.supinfo.food.services.UserService;
import com.supinfo.food.services.UserServiceService;
import com.supinfo.food.services.UserServiceServiceLocator;
import com.supinfo.youfood.template.Template;

/**
 * Liste des utilisateurs
 * @author Keitaro
 */
public class UserView extends Template {

	private Logger logger = Logger.getLogger(getClass());
	
	private List<User> listUsers;
	
	public UserView() {
		callService();
		createTable();
	}
	
	/**
	 * Call the webservice
	 */
	private void callService() {
		try {
			UserServiceService binding = new UserServiceServiceLocator();
			UserService service = binding.getUserService();
			listUsers = Arrays.asList(service.getAll());
		} catch (ServiceException e) {
			logger.info("Service can not be reached.");
		} catch (RemoteException e) {
			logger.info("Service does not responded.");
		}
	}

	/**
	 * Create table
	 * @return 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void createTable() {
		DataView dataView = new DataView("user", new ListDataProvider<>(
				listUsers)) {
			private static final long serialVersionUID = 1L;

			public void populateItem(final Item item) {
                final User user = (User) item.getModelObject();
                item.add(new Label("id", String.valueOf(user.getId())));
                item.add(new Label("login", user.getLogin()));
                
                Link link = new Link("linkDeleteUser") {
                	private static final long serialVersionUID = 1L;
					public void onClick() {
						// Appel au service
						try {
							UserServiceService binding = new UserServiceServiceLocator();
							UserService service = binding.getUserService();
							service.delete(user.getId());
						} catch (ServiceException e) {
							logger.info("Service can not be reached.");
						} catch (RemoteException e) {
							logger.info("Service does not responded.");
						}
						
						// Redirection
						setResponsePage(UserView.class);
					}
				};
				item.add(link);
            }
        };
        dataView.setItemsPerPage(10);
        add(dataView);
        add(new PagingNavigator("navigator", dataView));
	}
}
